package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.dto.RoleDTO;
import com.itheima.dto.UserDTO;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: bowen
 * @Date: 2019/7/22 15:11
 * @Description:
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    UserDao userDao;

    @Autowired
    RoleDao roleDao;

    @Autowired
    PermissionDao permissionDao;

    /**
     * @描述：根据用户名获取用户信息
     */
    @Override
    public UserDTO findByUsername(String username) {
        UserDTO userDto = new UserDTO();
        User user = userDao.selectOne(User.builder().username(username).build());
        if (ObjectUtils.isEmpty(user)) {
            return null;
        }
        // 根据用户id查询角色信息
        BeanUtils.copyProperties(user, userDto);
        Set<Role> roleList = roleDao.findRolesByUserId(user.getId());
        Set<RoleDTO> roleDTOList = new HashSet<>();
        if (!CollectionUtils.isEmpty(roleList)) {
            //	如果角色列表不为空，根据角色id查询权限信息
            roleList.forEach(role -> {
                RoleDTO roleDTO = new RoleDTO();
                BeanUtils.copyProperties(role, roleDTO);
                Set<Permission> permissionList = permissionDao.findByRoleId(role.getId());
                roleDTO.setPermissions(permissionList);
                roleDTOList.add(roleDTO);
            });
            userDto.setRoles(roleDTOList);
        }
        return userDto;
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<User> pages = userDao.findPage(queryString);
        return new PageResult(pages.getTotal(), pages.getResult());
    }

    @Override
    public void add(User user) {
        // 1. 添加用户
        userDao.add(user);
        // 2. 维护
    }
}
